"use client";
import React, { useState, useRef, useEffect } from "react";
import { useDrag } from "@use-gesture/react";
import { useSpring, animated } from "@react-spring/web";

interface SwipeProps {
    items: Array<{ id: string | number; content: React.ReactNode }>;
}

const Swipe = ({ items }: SwipeProps) => {
    const containerRef = useRef<HTMLDivElement>(null);
    const [containerWidth, setContainerWidth] = useState(0);
    const [currentIndex, setCurrentIndex] = useState(0);
    const [isDragging, setIsDragging] = useState(false);

    // 获取容器宽度并监听窗口变化
    useEffect(() => {
        const updateWidth = () => {
            if (containerRef.current) {
                setContainerWidth(containerRef.current.offsetWidth);
            }
        };

        updateWidth();
        window.addEventListener("resize", updateWidth);
        return () => window.removeEventListener("resize", updateWidth);
    }, []);

    // 动画配置
    const [spring, api] = useSpring(() => ({
        x: -currentIndex * containerWidth,
        config: { tension: 300, friction: 30 },
    }));

    // 手势处理
    const bind = useDrag(
        ({ active, movement: [mx], direction: [dx], velocity }) => {
            setIsDragging(active);

            if (active) {
                api.start({
                    x: -currentIndex * containerWidth + mx,
                    immediate: true,
                });
            } else {
                const threshold = containerWidth * 0.3;
                const velocityThreshold = 0.5;
                const newIndex = Math.max(
                    0,
                    Math.min(
                        items.length - 1,
                        currentIndex +
                            (mx > threshold ||
                            (velocity[0] > velocityThreshold && dx > 0)
                                ? -1
                                : mx < -threshold ||
                                  (velocity[0] > velocityThreshold && dx < 0)
                                ? 1
                                : 0)
                    )
                );

                setCurrentIndex(newIndex);
                api.start({ x: -newIndex * containerWidth });
            }
        },
        {
            axis: "x",
            filterTaps: true,
            rubberband: 0.2,
            bounds: {
                left:
                    currentIndex === items.length - 1
                        ? -containerWidth * 0.3
                        : -Infinity,
                right: currentIndex === 0 ? containerWidth * 0.3 : Infinity,
            },
        }
    );

    // 虚拟渲染计算
    const renderRange = 1; // 预渲染范围
    const startIdx = Math.max(0, currentIndex - renderRange);
    const endIdx = Math.min(items.length - 1, currentIndex + renderRange);
    const visibleItems = items.slice(startIdx, endIdx + 1);

    return (
        <div
            ref={containerRef}
            style={{
                overflow: "hidden",
                position: "relative",
                width: "100%",
                touchAction: "pan-y",
            }}
        >
            <animated.div
                {...bind()}
                style={{
                    display: "flex",
                    width: `${containerWidth * items.length}px`,
                    transform: spring.x.to((x) => `translateX(${x}px)`),
                }}
            >
                {visibleItems.map((item, index) => {
                    const itemIndex = startIdx + index;
                    return (
                        <div
                            key={item.id}
                            style={{
                                width: `${containerWidth}px`,
                                flexShrink: 0,
                                pointerEvents: isDragging ? "none" : "auto",
                                position: "relative",
                                left: `${itemIndex * containerWidth}px`,
                            }}
                        >
                            {item.content}
                        </div>
                    );
                })}
            </animated.div>
        </div>
    );
};

export default function Page() {
    const items = [
        {
            id: 1,
            content: <div className="w-full h-[200px]">1</div>,
        },
        {
            id: 2,
            content: <div className="w-full h-[200px]">2</div>,
        },
        {
            id: 3,
            content: <div className="w-full h-[200px]">3</div>,
        },
        {
            id: 4,
            content: <div className="w-full h-[200px]">4</div>,
        },
    ];
    return <Swipe items={items} />;
}
